#include "array_and_file.c"
#define MAX 9000

void merge_sort (int *array, int file_size, char *unsorted_input_file, char *sorted_output_file)
{
        read_file_into_array (array, file_size, unsorted_input_file);
        partition(array, 0, file_size - 1);
        write_array_to_file (array, file_size, sorted_output_file);
}

void partition(int *arr,int low,int high){

    int mid;

    if(low<high){
         mid=(low+high)/2;
         partition(arr,low,mid);
         partition(arr,mid+1,high);
         merge_arrays(arr,low,mid,high);
    }
}

void merge_arrays(int *arr,int low,int mid,int high){

    int i,m,k,l,temp[MAX];

    l=low;
    i=low;
    m=mid+1;

    while((l<=mid)&&(m<=high)){

         if(arr[l]<=arr[m]){
             temp[i]=arr[l];
             l++;
         }
         else{
             temp[i]=arr[m];
             m++;
         }
         i++;
    }

    if(l>mid){
         for(k=m;k<=high;k++){
             temp[i]=arr[k];
             i++;
         }
    }
    else{
         for(k=l;k<=mid;k++){
             temp[i]=arr[k];
             i++;
         }
    }

    for(k=low;k<=high;k++){
         arr[k]=temp[k];
    }
}
